package logic

import (
	"context"
	"fmt"
	"user/model/mysql"
	"user/model/redisInit"
	"user/pkg"
	"user/userrpc/internal/svc"
	"user/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRegisterLogic {
	return &UserRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserRegisterLogic) UserRegister(in *userrpc.UserRegisterRequest) (*userrpc.UserRegisterResponse, error) {
	// todo: add your logic here and delete this line

	get := redisInit.Client.Get("captcha" + "register" + in.Username)
	if get.Val() != in.Captcha {
		return nil, fmt.Errorf("图形验证码错误")
	}
	//cmd := redisInit.Client.Get("sendSms" + "register" + in.Username)
	//if cmd.Val() != in.SendSms {
	//	return nil, fmt.Errorf("短信验证码错误")
	//}
	var user mysql.User
	mysql.DB.Debug().Where("username = ", in.Username).Find(&user)
	if user.ID != 0 {
		return nil, fmt.Errorf("账号已注册,请重新注册")
	}
	m := mysql.User{
		Username: in.Username,
		Password: pkg.MD5(in.Password),
	}
	mysql.DB.Debug().Create(&m)
	return &userrpc.UserRegisterResponse{
		Id: int64(m.ID),
	}, nil
}
